package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Booking;
import model.BookingIO;
import model.Users;

/**
 * Servlet implementation class BookingHistory
 */
public class BookingHistory extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BookingHistory() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * On a post, the BookingHistory servlet gets the username from the session
	 * and then gets the id from the name. All bookings are retrieved that are
	 * associated with that user name. The bookings are forwarded to the 
	 * BookingHistory.jsp page to be displayed. 
	 * 
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Get session object
		HttpSession session = request.getSession();
		
		//Declare objects for models
		BookingIO bookingIO = new BookingIO();
		Users users = new Users();
		
		//Get user name from session
		String userName = (String) session.getAttribute("user");
		
		//Get user id from user name
		int userID = users.getUserID(userName);
		
		//Get all bookings for the user id
		ArrayList<Booking> bookings = bookingIO.getBookings(userID);
		
		//Set the bookings in the request
		request.setAttribute("bookings", bookings);
		
		//Encode URL
		String url = "/WEB-INF/BookingHistory.jsp";
		url = response.encodeURL(url);
		
		//Forward to BookingHistory.jsp
		RequestDispatcher requestDispatcher;
		requestDispatcher = request.getRequestDispatcher(url);
		requestDispatcher.forward(request, response);
	}
}
